import React, { Component } from 'react';
import { Link } from 'react-router-dom';
import { Table, Pagination, Grid, Button, MenuButton } from '@alifd/next';
import IceContainer from '@icedesign/container';
import FoundationSymbol from '@icedesign/foundation-symbol';
import RequestNoteListFilter from './TableFilter';
import { noteTypes } from '../../../../conf/noteTypeConfig';
import request from '../../../../instances/request';

const { Row, Col } = Grid;

export default class SearchTable extends Component {
  static displayName = 'SearchTable';

  static propTypes = {};

  static defaultProps = {};

  constructor(props) {
    super(props);
    this.state = {
      currentPage: 1,
      requestNoteList: [],
      __loading: true,
      total: 0,
      pageSize: props.limit,
      sStr: '',
      sType: '',
      sStatus: '',
      sTime: null,
    };
  }

  handlePaginationChange = (current) => {
    console.log(current);
    let { sStr, sType, sStatus, sTime } = this.state;
    this.setState({
      currentPage: current,
    }, () => {
      this.fetchAndSetData({
        page: current,
        sStr,
        sType,
        sStatus,
        sTime
      })
    });
  };

  renderStatus = (value, index, record) => {
    switch ( record.status ) {
      case '未提交':
        return <div className='badge badge-un-commit'>{record.status}</div>;
      case '审批中':
        return <div className='badge badge-on-approve'>{record.status}</div>;
      case '进行中':
        return <div className='badge badge-on-run'>{record.status}</div>;
      case '已关闭':
        return <div className='badge badge-closed'>{record.status}</div>;
      case '未通过':
        return <div className='badge badge-un-passed'>{record.status}</div>;
      default:
        return <div>不明状态</div>;
    }
  };

  renderOper = (value, index, record) => {
    switch ( record.status ) {
      case '未提交':
        return (
          <div>
            <Link style={styles.link} to={{
              pathname: '/staff/requestNote',
              search: `?oid=${record.oid}&ut=com`,
            }}>继续编辑</Link>
          </div>
        );
      default:
        return (
          <div>
            <Link style={styles.link} to={{
              pathname: '/staff/requestNote',
              search: `?oid=${record.oid}&ut=com`,
            }}>查看详情</Link>
          </div>
        );
    }
  };

  async getRequestNoteList({ page = 1, limit, requestType = 'user', sStr, sType, sStatus, sTime }) {
    let res = await request
      .post('/staff/requestNote/list', {
        page,
        limit: limit || this.props.limit,
        requestType,
        sStr,
        sType,
        sStatus,
        sTime,
      });
    let { code, msg } = res.data;
    return {
      code,
      requestNoteList: msg.requestNoteList,
      total: msg.total,
    }
  }

  async fetchAndSetData({ page = 1, limit, requestType = 'user', sStr, sType, sStatus, sTime }) {
    this.setState({
      __loading: true,
    });
    let { code, requestNoteList, total } = await this.getRequestNoteList({
      page: page,
      limit: limit || this.props.limit,
      requestType,
      sStr,
      sType,
      sStatus,
      sTime,
    });
    this.setState({
      requestNoteList: requestNoteList,
      total: total,
      currentPage: page,
      __loading: false,
    })
  }

  handleSearch({ sStr, sTime, sType, sStatus }) {
    let self = this;
    return function(e) {
      e.preventDefault();
      self.setState({
        sStr,
        sTime,
        sType,
        sStatus,
      });
      self.fetchAndSetData({
        sStr,
        sType,
        sStatus,
        sTime,
      });
    }
  }

  async componentDidMount() {
    await this.fetchAndSetData({page: 1});
  }

  render() {
    return (
      <IceContainer style={{padding: '0 0 20px 0',}}>
        <Row>
          <Col>
            <div style={{ height: '60px', background: '#EAEBEF' }}>
              <div style={
                {
                  float: 'left',
                  fontSize: '20px',
                  fontWeight: 'bold',
                  height: '60px',
                  lineHeight: '60px',
                  paddingLeft: '30px',
                }
              }>
                {/*// todo: 为什么这里FoundationSymbol和span同时Align就会出错，并不居中？*/}
                <FoundationSymbol type='publish' style={{ display: 'inline', verticalAlign: 'middle' }}/>
                <span>&nbsp;申请列表</span>
              </div>
              <div  style={
                {
                  float: 'right',
                  lineHeight: '60px',
                  paddingRight: '20px',
                }
              }>
                <MenuButton type='primary' popupTriggerType='hover' label='添加申请单' size='medium' style={styles.menuButton}>
                  {
                    noteTypes.map((ele, idx) => {
                      return (
                        <MenuButton.Item key={idx}><Link to={{
                          pathname: '/staff/requestNote',
                          search: `?type=${ele.enName}&ut=cc`,
                          state: { fromDashboard: true },
                        }}>{ele.name}</Link></MenuButton.Item>
                      )
                    })
                  }
                </MenuButton>
              </div>
              <div style={{ clear: 'both' }} />
            </div>
          </Col>
        </Row>
        <RequestNoteListFilter  handleSearch={this.handleSearch.bind(this)}/>
        <Table
          isZebra={true}
          loading={this.state.__loading}
          dataSource={this.state.requestNoteList}
          hasBorder={false}
          style={{ padding: '0 20px 20px' }}
        >
          <Table.Column title="编号" dataIndex="oid" />
          <Table.Column
            title="标题"
            cell={(value, index, record) => {
              return (
                <Link style={styles.link} to={{
                  pathname: '/staff/requestNote',
                  search: `?oid=${record.oid}&ut=com`,
                }}>
                  <div style={{ width: '250px', height: '18px', lineHeight: '18px', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>
                    { record.title }
                  </div>
                </Link>
              )
            }}
          />
          <Table.Column title="类型" dataIndex="type" />
          <Table.Column
            title="状态"
            dataIndex="status"
            cell={this.renderStatus}
          />
          <Table.Column title="创建时间" dataIndex="createdAt" />
          <Table.Column
            title="操作"
            dataIndex="oper"
            cell={this.renderOper}
          />
        </Table>
        <Pagination
          style={styles.pagination}
          current={this.state.currentPage}
          total={this.state.total}
          pageSize={this.state.pageSize}
          onChange={this.handlePaginationChange}
        />
      </IceContainer>
    );
  }
}

const styles = {
  link: {
    margin: '0 5px',
    color: 'rgba(49, 128, 253, 0.65)',
    cursor: 'pointer',
    textDecoration: 'none',
  },
  separator: {
    margin: '0 8px',
    display: 'inline-block',
    height: '12px',
    width: '1px',
    verticalAlign: 'middle',
    background: '#e8e8e8',
  },
  pagination: {
    textAlign: 'right',
    marginRight: '20px',
  },
  menuButton: {
    width: '200px',
  },
};
